package com.concurrent;

import java.util.concurrent.*;

/**
 * @Classname CountExample
 * @Description 5000次add操作，每次最多200个同时执行
 * @Created by xiangty
 */
public class CountExample {

    private static int threadTotal = 200;
    private static int clientTotal = 5000;

    private static long count = 0;

    public static void add(){
        count++;
    }

    public static void main(String[] args){

        // 线程不安全的
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        for (int i = 0; i < clientTotal; i++) {
            exec.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        exec.shutdown();
        System.out.println("---------------:" + count);



//        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
//        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

//        new ThreadPoolExecutor(int corePoolSize,                          // 默认线程数
//                                int maximumPoolSize,                      // 最大线程数
//                                long keepAliveTime,                       // 闲置线程等待时长
//                                TimeUnit unit,                            // 闲置线程等待时间单位
//                                BlockingQueue<Runnable> workQueue,        // 阻塞队列
//                                ThreadFactory threadFactory,              // 线程工厂
//                                RejectedExecutionHandler handler);        // 拒绝策略

//        拒绝策略
        // 直接拒绝抛出异常
//        ThreadPoolExecutor.AbortPolicy
        // 将请求返回原来的线程处理
//        ThreadPoolExecutor.CallerRunsPolicy
        // 直接丢弃请求
//        ThreadPoolExecutor.DiscardPolicy
        // 丢弃时间等待时间最久的请求
//        ThreadPoolExecutor.DiscardOldestPolicy

    }


}
